package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;


import org.checkerframework.checker.units.qual.A;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {
    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqMessageService mqMessageService;
    /**
     * 查询手机号是否存在
     * 返回用户
     * */
    public User findByMobile(String phone){
        User user = userApi.findByMobile(phone);
        return user;
    }
    /**
     * 登入注册
     * 判断手机号是否是新用户
     * 判断验证码是否正确
     * 返回token  和 isNew
     * */
    public Map loginVerification(String phone, String code) {

        //获取redis中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CODE:" + phone);
        //判断验证码
        if (StringUtils.isEmpty(code)  || !redisCode.equals(code)){
            throw new BusinessException(ErrorResult.loginError());
        }
        redisTemplate.delete("CODE:" + phone);
        //查询用户是否存在
        User user = userApi.findByMobile(phone);
        Boolean isNew = false;
        String type = "0101";//登入
        if (user == null){
            //保存用户
             user = new User();
             user.setPassword("123456");
             user.setMobile(phone);
            Long userId = userApi.save(user);
            user.setId(userId);
            //将用户信息注册到环信
            huanXinTemplate.createUser("hx"+user.getId(),"123456");
            //更新环信账号和密码
            user.setHxUser("hx"+user.getId());
            user.setHxPassword("123456");
            userApi.update(user);
            isNew = true;
            type = "0102";
        }
        //登入成功发送消息
        mqMessageService.sendLogMessage(user.getId(),type,"log.user",null);


            //生存token 字符串
        Map map = new HashMap();
        map.put("id",user.getId());
        map.put("mobile",phone);
        String token = JwtUtils.getToken(map);
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;

    }
    //保存用户资料
    public void saveUserInfo(UserInfo userInfo) {
        userInfoApi.save (userInfo);
    }

    //设置头像
    public void setHead(Long id, MultipartFile headPhoto) throws IOException {
        //上传到 oss
        String imgUrl = ossTemplate.upload(headPhoto.getInputStream(), headPhoto.getOriginalFilename());
        //判断是否包含人脸
        Boolean detect = aipFaceTemplate.detect(imgUrl);
        if (!detect){
            String url = imgUrl.substring(47);
            ossTemplate.delete(url);
            throw new BusinessException(ErrorResult.faceError());

        }
        //根据id 设置用户头像
        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(imgUrl);
        userInfo.setId(id);
        userInfoApi.update(userInfo);

    }
    //根绝id 查询
    public User findById(Long userId) {
        User user = userApi.findById(userId);
        return user;
    }
    /**
     * 修改手机号
     * 判断验证码是否正确
     * */
    public Map checkVerificationCode(String mobile, String code) {
        //获取redis中的验证码
        String redisCode = (String) redisTemplate.opsForValue().get("CODE:" + mobile);
        Map map =new HashMap();
        //判断验证码
        if (StringUtils.isEmpty(code)  || !redisCode.equals(code)){
            map.put("verification",false);
        }else {

            map.put("verification",true);
            redisTemplate.delete("CODE:" + mobile);
        }
        return map;

    }
}
